#include "config.h"

#define DBG_SUBSYS S_LIBCONTROL

#include "lich_api.h"

#include "volume_ctl.h"
#include "volume_ctl_internal.h"

int volume_ctl_getbp(mcache_entry_t *cent, const char *key, uint32_t *bp)
{
        int ret;
        volume_proto_t *volume_proto;
        char value[MAX_INFO_LEN];
        int valuelen = MAX_INFO_LEN;

        memset(value, 0x00, MAX_INFO_LEN);

        ret = __volume_ctl_rdlock(cent);
        if (unlikely(ret))
                GOTO(err_ret, ret);

        // TODO use fileinfo
        volume_proto = cent->value;
        ret = volume_proto->xattr_get(volume_proto, key, value, &valuelen);
        if (unlikely(ret)) {
                if (ret == ENOKEY) {
                        *bp = 0;
                } else {
                        __volume_ctl_unlock(cent);
                        GOTO(err_ret, ret);
                }
        } else {
                *bp = atoi(value);
        }

        DINFO("vol "CHKID_FORMAT" get bp %d\n", CHKID_ARG(&volume_proto->chkid), *bp);

        __volume_ctl_unlock(cent);

        return 0;
err_ret:
        return ret;
}

int volume_ctl_setbp(mcache_entry_t *cent, const char *key, uint32_t bp)
{
        int ret;
        volume_proto_t *volume_proto;
        char value[MAX_INFO_LEN];
        int valuelen = MAX_INFO_LEN;

        sprintf(value, "%u", bp);
        valuelen = strlen(value);

        ret = __volume_ctl_rdlock(cent);
        if (unlikely(ret))
                GOTO(err_ret, ret);

        // TODO use fileinfo
        volume_proto = cent->value;
        ret = volume_proto->xattr_set(volume_proto, key, value, valuelen, 0);
        if (unlikely(ret)) {
                __volume_ctl_unlock(cent);
                GOTO(err_ret, ret);
        }

        DINFO("vol "CHKID_FORMAT" set bp %d\n", CHKID_ARG(&volume_proto->chkid), bp);

        __volume_ctl_unlock(cent);

        return 0;
err_ret:
        return ret;
}

int volume_ctl_rmbp(mcache_entry_t *cent, const char *key)
{
        int ret;
        volume_proto_t *volume_proto;

        ret = __volume_ctl_rdlock(cent);
        if (unlikely(ret))
                GOTO(err_ret, ret);

        // TODO use fileinfo
        volume_proto = cent->value;
        ret = volume_proto->xattr_remove(volume_proto, key);
        if (unlikely(ret)) {
                if (ret != ENOKEY) {
                        __volume_ctl_unlock(cent);
                        GOTO(err_ret, ret);
                }
        }

        __volume_ctl_unlock(cent);

        return 0;
err_ret:
        return ret;
}
